import React, { useState, useEffect, useMemo } from 'react';
import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Button,
  Space,
  Tag,
  Tooltip,
  Empty,
  Badge,
  Segmented,
  message,
  Modal,
  Drawer
} from 'antd';
import {
  SearchOutlined,
  AppstoreOutlined,
  BarsOutlined,
  FilterOutlined,
  StarOutlined,
  StarFilled,
  ClockCircleOutlined,
  FireOutlined,
  TeamOutlined,
  CopyOutlined,
  EditOutlined,
  EyeOutlined,
  ThunderboltOutlined,
  PlusOutlined
} from '@ant-design/icons';
import { PromptTemplate, PromptCategory } from '@/types/prompt';
import { PRESET_TEMPLATES, getCategoryLabel } from '@/constants/prompt-templates';
import { promptService } from '@/services/prompt.service';
import './style.css';

const { Search } = Input;
const { Option } = Select;

interface PromptLibraryProps {
  onSelectTemplate?: (template: PromptTemplate) => void;
  onPreviewTemplate?: (template: PromptTemplate) => void;
  onEditTemplate?: (template: PromptTemplate) => void;
  onCreateTemplate?: () => void;
  favorites?: string[];
  onToggleFavorite?: (templateId: string) => void;
  currentTemplateId?: string;
  showActions?: boolean;
}

const PromptLibrary: React.FC<PromptLibraryProps> = ({
  onSelectTemplate,
  onPreviewTemplate,
  onEditTemplate,
  onCreateTemplate,
  favorites = [],
  onToggleFavorite,
  currentTemplateId,
  showActions = true
}) => {
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<PromptCategory | 'all'>('all');
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [sortBy, setSortBy] = useState<'name' | 'usage' | 'updated'>('name');
  const [showOnlyFavorites, setShowOnlyFavorites] = useState(false);
  const [templates, setTemplates] = useState<PromptTemplate[]>([]);
  const [previewTemplate, setPreviewTemplate] = useState<PromptTemplate | null>(null);
  const [detailDrawerOpen, setDetailDrawerOpen] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<PromptTemplate | null>(null);

  // 加载模板数据
  useEffect(() => {
    loadTemplates();
  }, []);

  const loadTemplates = async () => {
    try {
      // 先加载预设模板作为默认数据
      const presetTemplateList = Object.entries(PRESET_TEMPLATES).map(([key, preset]) => ({
        ...preset,
        id: preset.id,
        version: 1,
        createdAt: new Date(),
        updatedAt: new Date(),
        isPublic: true,
        usageCount: 0 // Will be updated from API
      }));

      // 尝试从API加载真实数据
      try {
        const { data: apiTemplates } = await promptService.getPrompts({ isPublic: true });
        if (apiTemplates.length > 0) {
          setTemplates(apiTemplates);
        } else {
          setTemplates(presetTemplateList);
        }
      } catch (apiError) {
        console.warn('Failed to load templates from API, using presets:', apiError);
        setTemplates(presetTemplateList);
      }
    } catch (error) {
      console.error('Failed to load templates:', error);
      message.error('加载模板失败');
    }
  };

  // 获取所有可用的标签
  const allTags = useMemo(() => {
    const tagsSet = new Set<string>();
    templates.forEach(template => {
      template.tags.forEach(tag => tagsSet.add(tag));
    });
    return Array.from(tagsSet);
  }, [templates]);

  // 过滤和排序模板
  const filteredTemplates = useMemo(() => {
    let filtered = [...templates];

    // 按类别过滤
    if (selectedCategory !== 'all') {
      filtered = filtered.filter(t => t.category === selectedCategory);
    }

    // 按搜索词过滤
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(t =>
        t.name.toLowerCase().includes(query) ||
        t.description.toLowerCase().includes(query) ||
        t.systemPrompt.toLowerCase().includes(query) ||
        t.tags.some(tag => tag.toLowerCase().includes(query))
      );
    }

    // 按标签过滤
    if (selectedTags.length > 0) {
      filtered = filtered.filter(t =>
        selectedTags.every(tag => t.tags.includes(tag))
      );
    }

    // 只显示收藏
    if (showOnlyFavorites) {
      filtered = filtered.filter(t => favorites.includes(t.id));
    }

    // 排序
    filtered.sort((a, b) => {
      switch (sortBy) {
        case 'usage':
          return b.usageCount - a.usageCount;
        case 'updated':
          return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
        case 'name':
        default:
          return a.name.localeCompare(b.name);
      }
    });

    return filtered;
  }, [templates, selectedCategory, searchQuery, selectedTags, showOnlyFavorites, favorites, sortBy]);

  // 处理模板选择
  const handleSelectTemplate = (template: PromptTemplate) => {
    if (onSelectTemplate) {
      onSelectTemplate(template);
      message.success(`已选择模板: ${template.name}`);
    }
  };

  // 处理模板预览
  const handlePreviewTemplate = (template: PromptTemplate) => {
    setPreviewTemplate(template);
    if (onPreviewTemplate) {
      onPreviewTemplate(template);
    }
  };

  // 处理收藏切换
  const handleToggleFavorite = (e: React.MouseEvent, templateId: string) => {
    e.stopPropagation();
    if (onToggleFavorite) {
      onToggleFavorite(templateId);
      const isFavorite = favorites.includes(templateId);
      message.success(isFavorite ? '已取消收藏' : '已添加收藏');
    }
  };

  // 处理快速应用
  const handleQuickApply = (e: React.MouseEvent, template: PromptTemplate) => {
    e.stopPropagation();
    handleSelectTemplate(template);
  };

  // 处理查看详情
  const handleViewDetails = (template: PromptTemplate) => {
    setSelectedTemplate(template);
    setDetailDrawerOpen(true);
  };

  // 渲染网格视图的模板卡片
  const renderGridCard = (template: PromptTemplate) => {
    const isFavorite = favorites.includes(template.id);
    const isCurrent = currentTemplateId === template.id;

    return (
      <Col key={template.id} xs={24} sm={12} md={8} lg={6}>
        <Badge.Ribbon
          text={isCurrent ? '当前使用' : ''}
          color="green"
          style={{ display: isCurrent ? 'block' : 'none' }}
        >
          <Card
            className={`prompt-template-card ${isCurrent ? 'current' : ''}`}
            hoverable
            onClick={() => handleViewDetails(template)}
            actions={showActions ? [
              <Tooltip title="预览">
                <EyeOutlined onClick={(e) => {
                  e.stopPropagation();
                  handlePreviewTemplate(template);
                }} />
              </Tooltip>,
              <Tooltip title={isFavorite ? '取消收藏' : '收藏'}>
                {isFavorite ? (
                  <StarFilled
                    className="favorite-icon active"
                    onClick={(e) => handleToggleFavorite(e, template.id)}
                  />
                ) : (
                  <StarOutlined
                    className="favorite-icon"
                    onClick={(e) => handleToggleFavorite(e, template.id)}
                  />
                )}
              </Tooltip>,
              <Tooltip title="快速应用">
                <ThunderboltOutlined onClick={(e) => handleQuickApply(e, template)} />
              </Tooltip>
            ] : []}
          >
            <Card.Meta
              title={
                <div className="template-card-title">
                  <span>{template.name}</span>
                  <Tag color={getCategoryColor(template.category)}>
                    {getCategoryLabel(template.category)}
                  </Tag>
                </div>
              }
              description={
                <div className="template-card-content">
                  <div className="template-description">{template.description}</div>
                  <div className="template-meta">
                    <Space size={[0, 8]} wrap>
                      {template.tags.slice(0, 3).map(tag => (
                        <Tag key={tag} className="template-tag">{tag}</Tag>
                      ))}
                      {template.tags.length > 3 && (
                        <Tag className="template-tag">+{template.tags.length - 3}</Tag>
                      )}
                    </Space>
                  </div>
                  <div className="template-stats">
                    <Space>
                      <span>
                        <FireOutlined /> {template.usageCount}
                      </span>
                      <span>
                        <ClockCircleOutlined /> {formatDate(template.updatedAt)}
                      </span>
                    </Space>
                  </div>
                </div>
              }
            />
          </Card>
        </Badge.Ribbon>
      </Col>
    );
  };

  // 渲染列表视图的模板项
  const renderListItem = (template: PromptTemplate) => {
    const isFavorite = favorites.includes(template.id);
    const isCurrent = currentTemplateId === template.id;

    return (
      <Card
        key={template.id}
        className={`prompt-template-list-item ${isCurrent ? 'current' : ''}`}
        hoverable
        onClick={() => handleViewDetails(template)}
      >
        <Row align="middle">
          <Col flex="auto">
            <Space direction="vertical" size={0}>
              <Space>
                <span className="template-list-name">{template.name}</span>
                <Tag color={getCategoryColor(template.category)}>
                  {getCategoryLabel(template.category)}
                </Tag>
                {isCurrent && <Tag color="green">当前使用</Tag>}
              </Space>
              <div className="template-list-description">{template.description}</div>
              <Space size={[8, 8]} wrap>
                {template.tags.map(tag => (
                  <Tag key={tag} className="template-tag">{tag}</Tag>
                ))}
              </Space>
            </Space>
          </Col>
          <Col>
            <Space direction="vertical" align="center" size={4}>
              <div className="template-stats-vertical">
                <div><FireOutlined /> {template.usageCount}</div>
                <div><ClockCircleOutlined /> {formatDate(template.updatedAt)}</div>
              </div>
              {showActions && (
                <Space>
                  <Button
                    size="small"
                    icon={<EyeOutlined />}
                    onClick={(e) => {
                      e.stopPropagation();
                      handlePreviewTemplate(template);
                    }}
                  />
                  <Button
                    size="small"
                    icon={isFavorite ? <StarFilled /> : <StarOutlined />}
                    className={isFavorite ? 'favorite-active' : ''}
                    onClick={(e) => handleToggleFavorite(e, template.id)}
                  />
                  <Button
                    size="small"
                    type="primary"
                    icon={<ThunderboltOutlined />}
                    onClick={(e) => handleQuickApply(e, template)}
                  >
                    应用
                  </Button>
                </Space>
              )}
            </Space>
          </Col>
        </Row>
      </Card>
    );
  };

  return (
    <div className="prompt-library-container">
      {/* 搜索和筛选栏 */}
      <Card className="prompt-library-filters">
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} lg={8}>
            <Search
              placeholder="搜索模板名称、描述或标签"
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              onSearch={setSearchQuery}
              allowClear
              prefix={<SearchOutlined />}
            />
          </Col>
          <Col xs={12} sm={6} lg={4}>
            <Select
              value={selectedCategory}
              onChange={setSelectedCategory}
              style={{ width: '100%' }}
              placeholder="选择类别"
            >
              <Option value="all">全部类别</Option>
              <Option value="role">角色设定</Option>
              <Option value="style">风格样式</Option>
              <Option value="domain">专业领域</Option>
              <Option value="custom">自定义</Option>
            </Select>
          </Col>
          <Col xs={12} sm={6} lg={4}>
            <Select
              value={sortBy}
              onChange={setSortBy}
              style={{ width: '100%' }}
              placeholder="排序方式"
            >
              <Option value="name">名称排序</Option>
              <Option value="usage">使用次数</Option>
              <Option value="updated">更新时间</Option>
            </Select>
          </Col>
          <Col xs={24} sm={24} lg={8} style={{ textAlign: 'right' }}>
            <Space>
              <Button
                icon={<FilterOutlined />}
                onClick={() => setShowOnlyFavorites(!showOnlyFavorites)}
                type={showOnlyFavorites ? 'primary' : 'default'}
              >
                {showOnlyFavorites ? '显示全部' : '只看收藏'}
              </Button>
              <Segmented
                value={viewMode}
                onChange={setViewMode as any}
                options={[
                  { label: '网格', value: 'grid', icon: <AppstoreOutlined /> },
                  { label: '列表', value: 'list', icon: <BarsOutlined /> }
                ]}
              />
              {onCreateTemplate && (
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={onCreateTemplate}
                >
                  创建模板
                </Button>
              )}
            </Space>
          </Col>
        </Row>

        {/* 标签筛选 */}
        {allTags.length > 0 && (
          <Row style={{ marginTop: 16 }}>
            <Col span={24}>
              <Space size={[0, 8]} wrap>
                <span>标签筛选：</span>
                {allTags.map(tag => (
                  <Tag
                    key={tag}
                    className={`filter-tag ${selectedTags.includes(tag) ? 'active' : ''}`}
                    onClick={() => {
                      if (selectedTags.includes(tag)) {
                        setSelectedTags(selectedTags.filter(t => t !== tag));
                      } else {
                        setSelectedTags([...selectedTags, tag]);
                      }
                    }}
                  >
                    {tag}
                  </Tag>
                ))}
                {selectedTags.length > 0 && (
                  <Button
                    size="small"
                    type="link"
                    onClick={() => setSelectedTags([])}
                  >
                    清除筛选
                  </Button>
                )}
              </Space>
            </Col>
          </Row>
        )}
      </Card>

      {/* 模板展示区 */}
      <div className="prompt-library-content">
        {filteredTemplates.length === 0 ? (
          <Empty
            description={
              showOnlyFavorites
                ? '暂无收藏的模板'
                : searchQuery || selectedTags.length > 0
                ? '没有找到匹配的模板'
                : '暂无模板'
            }
          >
            {onCreateTemplate && (
              <Button type="primary" onClick={onCreateTemplate}>
                创建第一个模板
              </Button>
            )}
          </Empty>
        ) : viewMode === 'grid' ? (
          <Row gutter={[16, 16]}>
            {filteredTemplates.map(renderGridCard)}
          </Row>
        ) : (
          <Space direction="vertical" style={{ width: '100%' }} size={16}>
            {filteredTemplates.map(renderListItem)}
          </Space>
        )}
      </div>

      {/* 预览Modal */}
      <Modal
        title={previewTemplate?.name}
        open={!!previewTemplate}
        onCancel={() => setPreviewTemplate(null)}
        footer={[
          <Button key="copy" icon={<CopyOutlined />} onClick={() => {
            if (previewTemplate) {
              navigator.clipboard.writeText(previewTemplate.systemPrompt);
              message.success('已复制到剪贴板');
            }
          }}>
            复制
          </Button>,
          onEditTemplate && (
            <Button
              key="edit"
              icon={<EditOutlined />}
              onClick={() => {
                if (previewTemplate) {
                  onEditTemplate(previewTemplate);
                  setPreviewTemplate(null);
                }
              }}
            >
              编辑
            </Button>
          ),
          <Button
            key="apply"
            type="primary"
            icon={<ThunderboltOutlined />}
            onClick={() => {
              if (previewTemplate) {
                handleSelectTemplate(previewTemplate);
                setPreviewTemplate(null);
              }
            }}
          >
            应用模板
          </Button>
        ]}
        width={800}
      >
        {previewTemplate && (
          <Space direction="vertical" style={{ width: '100%' }} size={16}>
            <div>
              <strong>描述：</strong>
              <div>{previewTemplate.description}</div>
            </div>
            <div>
              <strong>系统提示词：</strong>
              <Card className="preview-content">
                <pre>{previewTemplate.systemPrompt}</pre>
              </Card>
            </div>
            {previewTemplate.variables.length > 0 && (
              <div>
                <strong>变量：</strong>
                <Space wrap>
                  {previewTemplate.variables.map(v => (
                    <Tag key={v.name} color="blue">
                      {v.name} ({v.type})
                    </Tag>
                  ))}
                </Space>
              </div>
            )}
            <div>
              <strong>标签：</strong>
              <Space wrap>
                {previewTemplate.tags.map(tag => (
                  <Tag key={tag}>{tag}</Tag>
                ))}
              </Space>
            </div>
          </Space>
        )}
      </Modal>

      {/* 详情Drawer */}
      <Drawer
        title={selectedTemplate?.name}
        placement="right"
        onClose={() => setDetailDrawerOpen(false)}
        open={detailDrawerOpen}
        width={600}
      >
        {selectedTemplate && (
          <Space direction="vertical" style={{ width: '100%' }} size={16}>
            <Card>
              <div className="template-detail-section">
                <h4>基本信息</h4>
                <div>类别：{getCategoryLabel(selectedTemplate.category)}</div>
                <div>版本：v{selectedTemplate.version}</div>
                <div>使用次数：{selectedTemplate.usageCount}</div>
                <div>创建时间：{formatDate(selectedTemplate.createdAt)}</div>
                <div>更新时间：{formatDate(selectedTemplate.updatedAt)}</div>
              </div>
            </Card>
            
            <Card>
              <div className="template-detail-section">
                <h4>描述</h4>
                <p>{selectedTemplate.description}</p>
              </div>
            </Card>

            <Card>
              <div className="template-detail-section">
                <h4>系统提示词</h4>
                <pre className="template-prompt-preview">
                  {selectedTemplate.systemPrompt}
                </pre>
              </div>
            </Card>

            {selectedTemplate.userPromptPrefix && (
              <Card>
                <div className="template-detail-section">
                  <h4>用户提示词前缀</h4>
                  <pre className="template-prompt-preview">
                    {selectedTemplate.userPromptPrefix}
                  </pre>
                </div>
              </Card>
            )}

            {selectedTemplate.variables.length > 0 && (
              <Card>
                <div className="template-detail-section">
                  <h4>变量定义</h4>
                  <Space direction="vertical" style={{ width: '100%' }}>
                    {selectedTemplate.variables.map(v => (
                      <div key={v.name} className="variable-item">
                        <Tag color="blue">{v.name}</Tag>
                        <span className="variable-type">类型: {v.type}</span>
                        {v.required && <Tag color="red">必需</Tag>}
                        {v.description && <div className="variable-desc">{v.description}</div>}
                        {v.defaultValue !== undefined && (
                          <div className="variable-default">默认值: {v.defaultValue}</div>
                        )}
                      </div>
                    ))}
                  </Space>
                </div>
              </Card>
            )}

            <Card>
              <div className="template-detail-section">
                <h4>标签</h4>
                <Space wrap>
                  {selectedTemplate.tags.map(tag => (
                    <Tag key={tag}>{tag}</Tag>
                  ))}
                </Space>
              </div>
            </Card>

            <Space style={{ width: '100%' }}>
              <Button
                icon={<CopyOutlined />}
                onClick={() => {
                  navigator.clipboard.writeText(selectedTemplate.systemPrompt);
                  message.success('已复制到剪贴板');
                }}
                block
              >
                复制提示词
              </Button>
              {onEditTemplate && (
                <Button
                  icon={<EditOutlined />}
                  onClick={() => {
                    onEditTemplate(selectedTemplate);
                    setDetailDrawerOpen(false);
                  }}
                  block
                >
                  编辑模板
                </Button>
              )}
              <Button
                type="primary"
                icon={<ThunderboltOutlined />}
                onClick={() => {
                  handleSelectTemplate(selectedTemplate);
                  setDetailDrawerOpen(false);
                }}
                block
              >
                应用模板
              </Button>
            </Space>
          </Space>
        )}
      </Drawer>
    </div>
  );
};

// 辅助函数
function getCategoryColor(category: PromptCategory): string {
  const colors: Record<PromptCategory, string> = {
    role: 'blue',
    style: 'green',
    domain: 'purple',
    custom: 'orange'
  };
  return colors[category] || 'default';
}

function formatDate(date: Date): string {
  const d = new Date(date);
  const now = new Date();
  const diffMs = now.getTime() - d.getTime();
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  
  if (diffDays === 0) {
    return '今天';
  } else if (diffDays === 1) {
    return '昨天';
  } else if (diffDays < 7) {
    return `${diffDays}天前`;
  } else if (diffDays < 30) {
    return `${Math.floor(diffDays / 7)}周前`;
  } else if (diffDays < 365) {
    return `${Math.floor(diffDays / 30)}月前`;
  } else {
    return `${Math.floor(diffDays / 365)}年前`;
  }
}

export default PromptLibrary;